package com.dcjt.firehotcarpad.moudle

import android.annotation.SuppressLint
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import androidx.recyclerview.widget.GridLayoutManager
import com.aries.library.fast.manager.LoggerManager
import com.aries.library.fast.module.activity.FastTitleActivity
import com.aries.library.fast.retrofit.FastObserver
import com.aries.library.fast.util.SPUtil
import com.aries.library.fast.util.ToastUtil
import com.aries.ui.view.title.TitleBarView
import com.aries.ui.widget.progress.UIProgressView
import com.dcjt.firehotcarpad.R
import com.dcjt.firehotcarpad.adapter.CarConfigAdapter
import com.dcjt.firehotcarpad.adapter.MySpinnerAdapter
import com.dcjt.firehotcarpad.adapter.OnClickLisenter
import com.dcjt.firehotcarpad.base.ApiPath.RESULT_CODE
import com.dcjt.firehotcarpad.base.SPConstant
import com.dcjt.firehotcarpad.entity.CarDetailEntity
import com.dcjt.firehotcarpad.entity.JigouDetailEntity
import com.dcjt.firehotcarpad.retrofit1.repository.ApiRepository1
import com.dcjt.firehotcarpad.utils.AlertDialogUtil
import com.dcjt.firehotcarpad.utils.AlertViewUtil
import com.dcjt.firehotcarpad.utils.StringUtils
import com.dcjt.firehotcarpad.widget.CSIISpinner
import com.google.gson.Gson
import com.juntu.loginlib.contact.LoginConstant
import com.trello.rxlifecycle2.android.ActivityEvent
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity
import kotlinx.android.synthetic.main.activity_car_config.*

class CarConfigActivity : FastTitleActivity() {
    private var dialog: UIProgressView? = null
    private var currentDeptName: String? = null
    private var id_zhidui: String? = null
    private var dept_name_zhidui: String? = null
    private var id_dadui: String? = null
    private var dept_name_dadui: String? = null
    private var id_zhongdui: String? = null
    private var dept_name_zhongdui: String? = null
    private var mAdapter: CarConfigAdapter? = null
//    var adapter_zhidui: ArrayAdapter<JigouDetailEntity>? = null
    var adapter_zhidui: MySpinnerAdapter? = null
    var adapter_dadui: MySpinnerAdapter? = null
    var adapter_zhongdui: MySpinnerAdapter? = null
    override fun getContentLayout() = R.layout.activity_car_config
    override fun setTitleBar(titleBar: TitleBarView?) {
        titleBar?.setLeftTextDrawable(R.drawable.icon_back)?.setTitleMainText("绑定车辆")
            ?.setTitleMainTextSize(this.resources.getDimension(R.dimen.main_size))
            ?.setBackgroundColor(mContext.resources.getColor(R.color.mainColor))

        titleBar?.setOnLeftTextClickListener {
            finish()
        }
    }


    @SuppressLint("ResourceType")
    override fun initView(savedInstanceState: Bundle?) {
       var list_jg =  ArrayList<JigouDetailEntity>()
        list_jg.add(JigouDetailEntity())
        mAdapter = CarConfigAdapter(mContext, ArrayList<CarDetailEntity>())
        rv_contentFastLib1.layoutManager = GridLayoutManager(mContext, 3)
        rv_contentFastLib1.adapter = mAdapter
        mAdapter!!.notifyDataSetChanged()
        mAdapter!!.setOnClick(object : OnClickLisenter {
            override fun setOnclick(detail: CarDetailEntity) {
                //弹出弹出框
                AlertDialogUtil.alertTips(mContext,
                    resources.getString(R.string.tips), mContext.resources.getString( R.string.car_config_message),
                    {
                        //
                    }, {
                        //确定
                        com.juntu.loginlib.util.LoginUtil.saveSp(LoginConstant.USER_PSW, "")
                        SPUtil.put(mContext, SPConstant.CAR_CONFIG_ID, detail.id)
                        SPUtil.put(mContext, SPConstant.CAR_CONFIG_NAME,currentDeptName+"-"+ StringUtils.getNoNullString(detail.clmc,"")+"-"+  StringUtils.getNoNullString(detail.cphm,""))
                        val intent: Intent = intent
                        setResult(RESULT_CODE, intent)
                        finish()
                    }, negativeBtn = "取消", positiveBtn = "确定"
                )
            }
        })


        adapter_zhidui = MySpinnerAdapter(mContext,list_jg)
        sp_zhidui.setAdapter(adapter_zhidui)
        sp_zhidui.setOnClickListener( CSIISpinner.OnClickListener() {
            getJigouList("", adapter_zhidui!!,1)
        })

        adapter_dadui = MySpinnerAdapter(mContext,list_jg)
        sp_dadui.setAdapter(adapter_dadui)
        sp_dadui.setOnClickListener( CSIISpinner.OnClickListener() {
            if (StringUtils.isEmpty(id_zhidui)){
                ToastUtil.show("请选择上级机构")
                return@OnClickListener
            }
            id_zhidui?.let { getJigouList(it, adapter_dadui!!,2) }
        })

        adapter_zhongdui = MySpinnerAdapter(mContext,list_jg)
        sp_zhongdui.setAdapter(adapter_zhongdui)
        sp_zhongdui.setOnClickListener( CSIISpinner.OnClickListener() {
            if (StringUtils.isEmpty(id_dadui)){
                ToastUtil.show("请选择上级机构")
                return@OnClickListener
            }
            id_dadui?.let { getJigouList(it, adapter_zhongdui!!,3) }
        })


        sp_zhidui.setSelection(0,true)
        sp_dadui.setSelection(0,true)
        sp_zhongdui.setSelection(0,true)

        sp_zhidui.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
                TODO("Not yet implemented")
            }

            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (adapter_zhidui!!.getItem(position)!= null){
                    id_zhidui =   (adapter_zhidui!!.getItem(position) as JigouDetailEntity).id
                    dept_name_zhidui =   (adapter_zhidui!!.getItem(position) as JigouDetailEntity).dept_name
                    getCarList(id_zhidui!!,dept_name_zhidui!!)
                    if (adapter_zhongdui?.getSinnerData()?.size!! >0){
                        sp_zhongdui.setSelection(0,true)
                    }
                    if (adapter_dadui?.getSinnerData()?.size!! >0){
                        sp_dadui.setSelection(0,true)
                    }
                }

            }

        })
        sp_dadui.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
                TODO("Not yet implemented")
            }

            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (adapter_dadui!!.getItem(position)!= null){
                    id_dadui =   (adapter_dadui!!.getItem(position) as JigouDetailEntity).id
                    dept_name_dadui =   (adapter_dadui!!.getItem(position) as JigouDetailEntity).dept_name
                    getCarList(id_dadui!!,dept_name_dadui!!)
                    if (adapter_zhongdui?.getSinnerData()?.size!! >0) {
                        sp_zhongdui.setSelection(0,true)
                    }
                }
            }
        })
        sp_zhongdui.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
                TODO("Not yet implemented")
            }

            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (adapter_zhongdui!!.getItem(position)!= null){
                    id_zhongdui =   (adapter_zhongdui!!.getItem(position) as JigouDetailEntity).id
                    dept_name_zhongdui =   (adapter_zhongdui!!.getItem(position) as JigouDetailEntity).dept_name
                    if (!StringUtils.isEmpty(id_zhongdui)&& !StringUtils.isEmpty(dept_name_zhongdui)){
                        getCarList(id_zhongdui!!,dept_name_zhongdui!!)
                    } else{
                        ToastUtil.show("数据错误")
                    }

                }
            }
        })
    }

    private fun getCarList(jgid: String,dept_name:String) {
        if (StringUtils.isEmpty(jgid)){
            return
        }
        ApiRepository1.getInstance().getCarList(jgid)
            .compose((mContext as RxAppCompatActivity).bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(object : FastObserver<List<CarDetailEntity>>() {


                override fun _onError(errorRes: Int, errorCode: Int, e: Throwable) {
                    super._onError(errorRes, errorCode, e)
                    ToastUtil.show("获取车辆失败")

                }

                override fun _onNext(entity: List<CarDetailEntity>) {
                    if (entity != null && entity.size > 0) {
                        currentDeptName = dept_name
                        mAdapter?.setNewData(entity)
                        mAdapter?.notifyDataSetChanged()
                    }
                }

            })
    }

    private fun getJigouList(jgid: String, spinnerAdpter:MySpinnerAdapter,tag:Int) {
        ApiRepository1.getInstance().getJigouList( jgid)
            .compose((mContext as RxAppCompatActivity).bindUntilEvent(ActivityEvent.DESTROY))
            .subscribe(object : FastObserver<List<JigouDetailEntity>>() {


                override fun _onError(errorRes: Int, errorCode: Int, e: Throwable) {
                    super._onError(errorRes, errorCode, e)
                    ToastUtil.show("获取机构失败")

                }

                override fun _onNext(entity: List<JigouDetailEntity>) {
                    LoggerManager.d(Gson().toJson(entity))

                    //在子线程中想要 Toast 的地方添加如下

                        if (entity != null &&entity.size>0) {
                            if (spinnerAdpter != null  ){
                                spinnerAdpter.setNewList(entity)
                                spinnerAdpter.addDataIndex(JigouDetailEntity(),0)
                                spinnerAdpter.notifyDataSetChanged()
                                when(tag){
                                    1-> {sp_zhidui.performClick()}
                                    2-> {sp_dadui.performClick()}
                                    3->  {sp_zhongdui.performClick()}
                                    else  ->{ }
                                }

                            }
                        }



                }

            })
    }


    override fun getOrientation(): Int {
        return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
    }
}
